package com.imti.filedemo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewDebug.FlagToString;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    private TextView mTextConfigContent;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        initSharedPreference();

//        writeInternalFile();
        readInternalFile();
    }

    private void writeInternalFile()
    {
        try
        {
            //内部存储文件操作中：
            //同一个文件使用Context.MODE_PRIVATE 权限会覆盖原有内容（r&w）
            //Context.MODE_APPEND 权限会追加数据(w)
            FileOutputStream fos =
                openFileOutput("Hello_internal_file.txt", Context.MODE_PRIVATE);

            //方法1：
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
//            writer.write("Hello Internal File");

//            writer.close();

            //方法2
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            String text = "Hello Internal";
            bos.write(text.getBytes());

            bos.flush();
            bos.close();

        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void readInternalFile()
    {
        try
        {
            //通过文件名获取文件流，若文件不存在则返回null
            FileInputStream fis = openFileInput("Hello_internal_file.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

            StringBuffer sb = new StringBuffer();
            String text = null;
            while ((text = reader.readLine()) != null)
            {
                sb.append(text);
            }

            mTextConfigContent.setText(sb.toString());

        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void initSharedPreference()
    {
        //父类Context的方法，
        //Fragment中需要通过requireActivity().getSharedPreferences()调用
        //参数1：生成的xml文件名
        //参数2：访问权限
        //Context.MODE_PRIVATE 可读可写权限
        SharedPreferences sp =
            getSharedPreferences("test_share", Context.MODE_PRIVATE);

        //获取编辑器
        Editor editor = sp.edit();

        //添加数据
        editor.putBoolean("test_boolean", true);
        editor.putFloat("test_float", 3.14f);
        editor.putInt("test_integer", 123);
        editor.putLong("test_long", 123456789);
        editor.putString("test_string", "test");

        //提交
        //commit()为同步方法，数据量较大时，可能会卡顿主线程
        //apply()为异步方法，通过后台线程提交，不影响主线程
//        editor.commit();
        editor.apply();
//===========================获取数据===============================//
        //获取数据
        SharedPreferences sp2 =
            getSharedPreferences("test_share", Context.MODE_PRIVATE);

        //参数1：为保存时的key
        //参数2：为key不存在时的默认值
        boolean testBool = sp2.getBoolean("test_boolean", false);
        int testInt = sp2.getInt("test_integer", 0);
        float testFloat = sp2.getFloat("test_float", 0.0f);
        long testLong = sp2.getLong("test_long", -1);
        String strData = sp2.getString("test_string", "");

        Log.d(TAG, "SharedPreferences test_boolean：" + testBool);
        Log.d(TAG, "SharedPreferences test_integer：" + testInt);
        Log.d(TAG, "SharedPreferences test_float：" + testFloat);
        Log.d(TAG, "SharedPreferences test_long：" + testLong);
        Log.d(TAG, "SharedPreferences test_string：" + strData);
    }

    private void initView()
    {
        Button btnPlaySound = findViewById(R.id.btn_play_sound);
        Button btnReadConfig = findViewById(R.id.btn_read_config);
        mTextConfigContent = findViewById(R.id.text_config_content);

        btnReadConfig.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //获取文件流
//                InputStream is = getResources().openRawResource(R.raw.config);
                try
                {
                    //获取assets目录文件输入流
                    AssetManager am = getAssets();
                    InputStream is = am.open("assets_config.txt");
                    //BufferReader
                    BufferedReader reader =
                        new BufferedReader(new InputStreamReader(is));

                    StringBuffer sb = new StringBuffer();
                    String str = null;

                    while ((str = reader.readLine()) != null)
                    {
                        sb.append(str);
                    }

                    mTextConfigContent.setText(sb.toString());
                    //读取输入流数据字符串
//                    textConfigContent.setText(readFile(is));
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        });

        btnPlaySound.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //播放铃声音频
                MediaPlayer.create(MainActivity.this, R.raw.duang).start();
            }
        });
    }

    private String readFile(InputStream is)
    {
        byte[] bytes = new byte[1024];
        int n = 0;
        String str = "";
        try
        {
            while (((n = is.read(bytes)) != -1))
            {
                str = new String(bytes, 0, n);
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return str;
    }
}